package atguigu.time_table_interceptor;

import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class MyTimestamp_tableInterceptor implements Interceptor {
    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {

        //1 获取event的body,并且转化成utf-8的字符串
        String bodystring = new String(event.getBody(), StandardCharsets.UTF_8);
        //2 根据body的内容获取json对象
        JSONObject jsonObject = JSONObject.parseObject(bodystring);
        //3 根据获取到的json对象，获取表名和时间戳
        String table = jsonObject.getString("table");
        Long ts = jsonObject.getLong("ts") * 1000 ;
        //4 放置到头部
        event.getHeaders().put("tableName",table);
        event.getHeaders().put("timestamp",String.valueOf(ts));
        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        //批量处理事件，调用intercept方法
        for (Event event : list) {
            intercept(event);
        }
        return list;
    }

    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder{

        @Override
        public Interceptor build() {
            //返回构造器对象
            return new MyTimestamp_tableInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }

}
